package assets
{
	import away3d.textures.ATFCubeTexture;
	import away3d.textures.ATFTexture;
	
	import events.LoadedEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	/**
	 * 新的atf格式的贴图资源，能显著的优化RAM使用量（如当前服务器对下载资源的格式有限制则使用AssetAtfTextureWithZIP）
	 */	
	public class AssetAtfTexture extends EventDispatcher
	{
		private var loadingList:Array = new Array;
		private var currentLoadingURL:String;
		private var loader:URLLoader;
		
		private var _isCubeLIst:Array = new Array;
		private var _isCube:Boolean;
		
		public function AssetAtfTexture()
		{
			loader = new URLLoader;
			loader.dataFormat = URLLoaderDataFormat.BINARY; 
			loader.addEventListener(IOErrorEvent.IO_ERROR,onError);
		}
		
		private function onError(e:IOErrorEvent):void
		{
			var errorInfo:String ="没有此资源："+ currentLoadingURL;
			throw new Error(errorInfo);
		}
		
		public function load(URL:String,isCubeTexture:Boolean = false):void
		{
			if(loadingList.indexOf(URL) > -1)return;
			
			if(Asset.resBitmapDatas[URL] == undefined)
			{
				loadingList.push(URL);
				_isCubeLIst.push(isCubeTexture);
				
				if(loadingList.length==1)loadNext();
				
			}else{
				dispatchEvent(new LoadedEvent(URL,LoadedEvent.TEXTURE_COMPLETE));
			}
		}
		
		///////////////////////////////////////////////
		private function loadNext():void
		{
			currentLoadingURL = loadingList[0];
			_isCube = _isCubeLIst[0];
			loader.addEventListener(Event.COMPLETE,onloadComplete);
			
			loader.load(new URLRequest(currentLoadingURL));
		}
		
		private function onloadComplete(e:Event):void
		{
			if(!_isCube)
			{
				var _texture:ATFTexture = new ATFTexture(loader.data); 
				Asset.resAtfTextures[currentLoadingURL] = _texture;
			}else
			{
				var _cubeTexture:ATFCubeTexture = new ATFCubeTexture(loader.data); 
				Asset.resAtfTextures[currentLoadingURL] = _cubeTexture;
			}
			
			loadingList.splice(0,1);
			_isCubeLIst.splice(0,1);
			loader.close();
			
			dispatchEvent(new LoadedEvent(currentLoadingURL,LoadedEvent.TEXTURE_COMPLETE));
			
			if(loadingList.length == 0)
			{
				loader.removeEventListener(Event.COMPLETE,onloadComplete);
				return;
			}
			
			loadNext();
		}
	}
}